<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\controller\Compress;
use app\common\model\Gallery as GalleryModel;
use app\common\model\GalleryCate;
use Qiniu\Auth;
use think\facade\View;
use think\Response;
use app\common\tool\Result;

class Gallery extends Base
{
    public array $titles = [1 => '图片', 2 => '视频', 3 => '音频'];

    public array $enable = [1 => '图库', 2 => '视频库', 3 => '音频库'];

    public function index(): Response
    {
        $param = $this->request->get();
        $where = ['cate' => $param['cate'], 'status' => 1, 'is_del' => 0];
        $that = GalleryModel::where($where)->page(intval($param['page']), intval($param['limit']))->order('id desc');
        if (!empty($param['keyword'])) {
            $that->whereLike('title', '%' . $param['keyword'] . '%');
        }
        $count = GalleryModel::where($where)->count();
        $data = $that->select()->each(function ($callback) {
            $callback['url'] = $callback['type'] == 1 ? $callback['url'] : config('gallery')['qiniu']['domain'] . $callback['url'];
            return $callback;
        });

        return Result::fastReturn(['code' => 0, 'data' => $data, 'count' => $count]);
    }

    public function open(): string
    {
        $param = $this->request->get();
        $cate = GalleryCate::where(['type' => $param['t'], 'status' => 1, 'is_del' => 0])->field('id,title')->select();
        $cateId = !$cate->isEmpty() ? $cate[0]['id'] : 0;
        $config = config('gallery')['qiniu'];

        return View::assign([
            'type' => $param['t'],
            'title' => $this->titles[$param['t']],
            'cate' => $cate,
            'param' => $param,
            'spec' => !empty($param['spec']) ? $param['spec'] : '',
            'editor' => !empty($param['editor']) ? $param['editor'] : "",
            'count' => $cateId ? GalleryModel::where(['cate' => $cateId, 'status' => 1, 'is_del' => 0])->count() : 0,
            'qiNiu' => [
                'open' => $config['open'],
                'url' => $config['uploadUrl'],
                'token' => $config['open'] ? $this->getQnToken() : ''
            ]
        ])->fetch();
    }

    public function upload(): Response
    {
        try {
            $file = $this->request->file();
            $param = $this->request->param();
            $config = config('gallery');
            if ($param['type'] == 1) {
                validate(
                    ['file' => 'filesize:' . $config['image']['filesize'] . '|fileExt:' . $config['image']['fileExt'] . ''],
                    [
                        'file.filesize' => '文件大小不能超过' . (intval($config['image']['filesize'] / 1024 / 1024)) . 'M',
                        'file.fileExt' => '文件格式不正确，仅支持【' . $config['image']['fileExt'] . '】格式',
                    ]
                )->check($file);
                $result = (new Compress($config['image']))->compressImg($file);
            } else if ($param['type'] == 2) {
                validate(
                    ['file' => 'filesize:' . $config['video']['filesize'] . '|fileExt:' . $config['video']['fileExt'] . ''],
                    [
                        'file.filesize' => '文件大小不能超过' . (intval($config['video']['filesize'] / 1024 / 1024)) . 'M',
                        'file.fileExt' => '文件格式不正确，仅支持【' . $config['video']['fileExt'] . '】格式',
                    ]
                )->check($file);
                $result = (new Compress($config['video']))->compressVideo($file);
            } else {
                validate(
                    ['file' => 'filesize:' . $config['audio']['filesize'] . '|fileExt:' . $config['audio']['fileExt'] . ''],
                    [
                        'file.filesize' => '文件大小不能超过' . (intval($config['audio']['filesize'] / 1024 / 1024)) . 'M',
                        'file.fileExt' => '文件格式不正确，仅支持【' . $config['audio']['fileExt'] . '】格式',
                    ]
                )->check($file);
                $result = (new Compress($config['audio']))->compressVideo($file);
            }
            if ($result['code'] != 1) return Result::fail($result['msg']);
            GalleryModel::create([
                'type' => 1,
                'cate' => $param['cate'],
                'title' => $result['result']['name'],
                'url' => $result['result']['url']
            ]);

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success('上传成功');
    }

    public function addOperate()
    {
        try {
            $param = $this->request->post();
            GalleryModel::create([
                'type' => 2,
                'cate' => $param['cate'],
                'title' => $param['title'],
                'url' => $param['key']
            ]);

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success('上传成功');
    }

    public function getQnToken(): string
    {
        try {
            $config = config('gallery')['qiniu'];
            $auth = new Auth($config['accessKey'], $config['secretKey']);
            $bucket = $config['bucket'];
            $token = $auth->uploadToken($bucket);

        } catch (\Exception $e) {

            return '';
        }

        return $token;
    }

    public function destroy(): Response
    {
        try {
            $param = $this->request->post();
            $list = GalleryModel::whereIn('id', $param['id'])->select();
            if ($list->isEmpty()) {
                return Result::fail('删除失败');
            }
            foreach ($list as $info) {
                if ($info['type'] == 1) {
                    if (file_exists('.' . $info['url'])) {
                        unlink('.' . $info['url']);
                    }
                } else {
                    $this->deleteQiNiu($info['url']);
                }
            }
            GalleryModel::whereIn('id', $param['id'])->delete();

        } catch (\Exception $e) {

            return Result::fail('删除失败：' . $e->getMessage());
        }

        return Result::success('已删除');
    }

    public function deleteQiNiu($key): bool
    {
        try {
            $config = config('gallery')['qiniu'];
            $auth = new Auth($config['accessKey'], $config['secretKey']);
            $bucketManager = new \Qiniu\Storage\BucketManager($auth, (new \Qiniu\Config()));
            $err = $bucketManager->delete($config['bucket'], $key);
            if (!$err[1]) {

                return true;
            }

            return false;
        } catch (\Exception $e) {

            return false;
        }
    }

    public function addGroup(): Response
    {
        $param = $this->request->post();
        GalleryCate::create($param);

        return Result::success('添加成功');
    }

    public function saveGroup(): Response
    {
        GalleryCate::update($this->request->post());

        return Result::success('已修改');
    }

    public function destroyGroup(): Response
    {
        try {
            $param = $this->request->post();
            $info = GalleryCate::where(['id' => $param['id']])->find();
            if (empty($info)) {
                return Result::fail('删除失败,分组不存在');
            }
            $list = GalleryModel::where(['cate' => $info['id']])->select();
            foreach ($list as $v) {
                if ($v['type'] == 1) {
                    if (file_exists('.' . $v['url'])) {
                        unlink('.' . $v['url']);
                    }
                } else {
                    $this->deleteQiNiu($v['url']);
                }
            }
            GalleryModel::whereIn('cate', $info['id'])->delete();
            GalleryCate::where('id', $param['id'])->delete();

        } catch (\Exception $e) {

            return Result::fail('删除失败：' . $e->getMessage());
        }

        return Result::success('已删除');
    }
}
